import sun.security.x509.IPAddressName;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:Tcp版本的回显客户端
 * Author: WJW
 * Date: 2024-08-24
 * Time: 17:50
 */
public class TcpEchoClinet {
    private Socket socket = null;

    public TcpEchoClinet(String serverIp,int serverPort) throws IOException {
        //由于tcp是可靠传输，因此socket里面就会保存ip和port的信息
        //因此此处的TcpEchoClient类就不必保存，可以直接传给socket对象
        socket = new Socket(serverIp,serverPort);
    }

    public void start(){
        System.out.println("客户端启动！");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerConsole = new Scanner(System.in);
            Scanner scannerNetwork = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while(true){
                //1.从控制台读取输入的字符串
                System.out.print("->");
                if(!scannerConsole.hasNext()){
                    break;
                }
                String request = scannerConsole.next();
                //2.把请求发送给服务器
                //这里需要使用println来发送，未了让服务器的请求结尾带\n。和服务器的scanner.next呼应
                writer.println(request);
                //通过flush主动刷新缓冲区，确保数据真的发出去了
                writer.flush();
                //3.从服务器读取响应
                String response = scannerNetwork.next();
                //4.把响应显示出来
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClinet clinet = new TcpEchoClinet("127.0.0.1",9090);
        clinet.start();
    }
}
